﻿using System.Configuration;
using System.IO;
using System.Text;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using GSQ.BusinessEntities;
using GSQ.BusinessLogic;


namespace GSQ.Rpt_s
{
    public class Reportes
    {
        public Reportes()
        {
            //cnn = new ConnectionInfo();
            //cnn.ServerName = DbServer;
            //cnn.DatabaseName = DbName;
            //cnn.UserID = DbUser;
            //cnn.Password = DbPassWord;
            //cnn.IntegratedSecurity = false;
            this.rpt = new ReportDocument();
        }

        #region Variables
        private SYSTEM_CONFIG systemConfig = new SystemConfigBL().Get();
        private string DbName = ConfigurationManager.AppSettings.Get("DbName");
        private string DbUser = ConfigurationManager.AppSettings.Get("DbUser");
        private string DbServer = ConfigurationManager.AppSettings.Get("DbServer");
        private string DbPassWord = ConfigurationManager.AppSettings.Get("DbPassWord");
        private string ReportName;
        ReportDocument rpt;
        #endregion

        #region Metodos Auxiliares
        private void Login()
        {
            TableLogOnInfo crTableLogonInfo = new TableLogOnInfo();
            ConnectionInfo crConnectionInfo = new ConnectionInfo();

            crConnectionInfo.DatabaseName = DbName;
            crConnectionInfo.ServerName = DbServer;
            crConnectionInfo.UserID = DbUser;
            crConnectionInfo.Password = DbPassWord;
            crConnectionInfo.IntegratedSecurity = false;
            crConnectionInfo.Type = ConnectionInfoType.SQL;

            crTableLogonInfo.ConnectionInfo = crConnectionInfo;
            crTableLogonInfo.ConnectionInfo.DatabaseName = DbName;

            foreach (Table crTable in rpt.Database.Tables)
            {
                crTable.ApplyLogOnInfo(crTableLogonInfo);
            }

            foreach (ReportDocument d in rpt.Subreports)
            {
                foreach (Table crTable in d.Database.Tables)
                {
                    crTable.ApplyLogOnInfo(crTableLogonInfo);
                }
            }
        }

        public void PrintToFile(string path, string text)
        {
            using (StreamWriter outfile = new StreamWriter(path)) outfile.Write(text);
        }

        public StreamReader StreamReportDocument(ReportDocument document, int linesPerLine, int charactersPerInch)
        {
            MemoryStream stream = new MemoryStream();
            ExportOptions expOptions = document.ExportOptions;
            expOptions.ExportFormatType = ExportFormatType.Text;
            expOptions.ExportFormatOptions = new TextFormatOptions() { CharactersPerInch = charactersPerInch, LinesPerPage = linesPerLine };
            ExportRequestContext req = new ExportRequestContext();
            req.ExportInfo = expOptions;
            stream = (System.IO.MemoryStream)rpt.FormatEngine.ExportToStream(req);
            stream.Position = 0;
            return new StreamReader(stream);
        }
        #endregion

        #region GetReports
        public ReportDocument GetFacturaTicket(decimal id, bool documentoOriginal)
        {
            ReportName = "fac-01";
            this.rpt.Load(systemConfig.RUTA_REPORTES + ReportName + ".rpt", OpenReportMethod.OpenReportByTempCopy);
            UTILIDADES utils = new UtilidadesBL().Get();
            rpt.SetParameterValue("paramTipoDocumento", documentoOriginal);
            rpt.SetParameterValue("paramIdFactura", id);
            rpt.SetParameterValue("companyName", utils.NOMBRE_CIA);
            rpt.SetParameterValue("companyAddress", utils.DIRECCION);
            rpt.SetParameterValue("companyTels", string.Format("{0}, {1}", utils.TELEFONO1, utils.TELEFONO2));
            rpt.SetParameterValue("companyFax", utils.FAX);
            rpt.SetParameterValue("companyRnc", utils.RNC);
            rpt.SetParameterValue("companyComent", string.Format("{0}", "NO ACEPTAMOS DEVOLUCIONES!!\nDe ningun tipo de partes electricas\nNi de piezas vendidas correctamente\n\nGRACIAS POR TU VISITA"));
            this.Login();
            return rpt;
        }

        public ReportDocument GetFacturaCarta(decimal id, bool documentoOriginal)
        {
            ReportName = "fac-00";
            this.rpt.Load(systemConfig.RUTA_REPORTES + ReportName + ".rpt", OpenReportMethod.OpenReportByTempCopy);
            rpt.SetParameterValue("paramIdFactura", id);
            rpt.SetParameterValue("paramTipoDocumento", documentoOriginal);
            this.Login();
            return rpt;
        }

        public ReportDocument GetCotizacion(decimal id, bool showCodReference)
        {
            ReportName = "Cotizacion-00";
            this.rpt.Load(systemConfig.RUTA_REPORTES + ReportName + ".rpt", OpenReportMethod.OpenReportByTempCopy);
            rpt.SetParameterValue("paramId", id);
            rpt.SetParameterValue("ShowCodReference", showCodReference);
            this.Login();
            return rpt;
        }

        public ReportDocument GetCompra(decimal id)
        {
            ReportName = "Inv-07";
            this.rpt.Load(systemConfig.RUTA_REPORTES + ReportName + ".rpt");
            this.rpt.SetParameterValue("paramId", id);
            this.Login();

            return rpt;
        }

        public ReportDocument GetAjusteInvetario(decimal id)
        {
            ReportName = "Inv-08";
            this.rpt.Load(systemConfig.RUTA_REPORTES + ReportName + ".rpt");
            this.rpt.SetParameterValue("paramId", id);
            this.Login();

            return rpt;
        }

        public ReportDocument GetDevolucionMercancia(decimal id, bool documentoOriginal)
        {
            ReportName = "Nc-00";
            this.rpt.Load(systemConfig.RUTA_REPORTES + ReportName + ".rpt", OpenReportMethod.OpenReportByTempCopy);
            rpt.SetParameterValue("paramIdFactura", id);
            rpt.SetParameterValue("paramTipoDocumento", documentoOriginal);
            this.Login();
            return rpt;
        }

        public ReportDocument GetNotaCredito(decimal id, bool documentoOriginal)
        {
            ReportName = "Nc-01";
            this.rpt.Load(systemConfig.RUTA_REPORTES + ReportName + ".rpt", OpenReportMethod.OpenReportByTempCopy);
            rpt.SetParameterValue("paramIdFactura", id);
            rpt.SetParameterValue("paramTipoDocumento", documentoOriginal);
            this.Login();
            return rpt;
        }
        #endregion

        #region Print
        public void PrintFacturaTicket(decimal id, bool documentoOriginal)
        {
            ReportDocument doc = GetFacturaTicket(id, documentoOriginal);
            doc.ReportDefinition.Sections[4].SectionFormat.EnableSuppress = true;
            RawPrinterHelper.SendStringToPrinter(systemConfig.PRINTER_NAME_CONTADO, StreamReportDocument(doc, 0, 12).ReadToEnd());
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 10; i++)
            {
                sb.AppendLine();
            }
            RawPrinterHelper.SendStringToPrinter(systemConfig.PRINTER_NAME_CONTADO, sb.ToString());
            //new printHelper("Factura",
            //                 StreamReportDocument(doc, 0, 12).ReadToEnd(),
            //                 systemConfig.PRINTER_NAME_CONTADO,
            //                 850,
            //                 545,
            //                 "courier new",
            //                 9,
            //                 true,
            //                 0);
            //rpt.ReportDefinition.Sections[4].ReportObjects["PáginaNdeM1"].ObjectFormat.EnableSuppress = true;
            // RawPrinterHelper.SendStringToPrinter(systemConfig.PRINTER_NAME_CREDITO, StreamReportDocument(rpt, 37, 12).ReadToEnd());
            //PrintToFile("d:\\value.txt", StreamReportDocument(rpt, 20, 12).ReadToEnd());
        }

        public void PrintFacturaCarta(decimal id, bool documentoOriginal)
        {
            ReportDocument doc = GetFacturaCarta(id, documentoOriginal);
            doc.ReportDefinition.Sections[4].SectionFormat.EnableSuppress = true;
            new printHelper("Factura",
                             StreamReportDocument(doc, 0, 12).ReadToEnd(),
                             systemConfig.PRINTER_NAME_CREDITO,
                             850,
                             545,
                             "courier new",
                             9,
                             true,
                             37);
            //rpt.ReportDefinition.Sections[4].ReportObjects["PáginaNdeM1"].ObjectFormat.EnableSuppress = true;
            // RawPrinterHelper.SendStringToPrinter(systemConfig.PRINTER_NAME_CREDITO, StreamReportDocument(rpt, 37, 12).ReadToEnd());
            //PrintToFile("d:\\value.txt", StreamReportDocument(rpt, 20, 12).ReadToEnd());
        }

        public void PrintCotizacion(decimal id, bool documentoOriginal)
        {
            ReportDocument doc = GetCotizacion(id, documentoOriginal);
            doc.ReportDefinition.Sections[4].SectionFormat.EnableSuppress = true;
            new printHelper("Cotizacion",
                             StreamReportDocument(doc, 0, 12).ReadToEnd(),
                             systemConfig.PRINTER_NAME_CREDITO,
                             850,
                             545,
                             "courier new",
                             9,
                             true,
                             37);
            //rpt.ReportDefinition.Sections[4].ReportObjects["PáginaNdeM1"].ObjectFormat.EnableSuppress = true;
            // RawPrinterHelper.SendStringToPrinter(systemConfig.PRINTER_NAME_CREDITO, StreamReportDocument(rpt, 37, 12).ReadToEnd());
            //PrintToFile("d:\\value.txt", StreamReportDocument(rpt, 20, 12).ReadToEnd());
        }

        public void PrintDevolucionMercancia(decimal id, bool documentoOriginal)
        {
            ReportDocument doc = GetDevolucionMercancia(id, documentoOriginal);
            doc.ReportDefinition.Sections[4].SectionFormat.EnableSuppress = true;
            new printHelper("Nota Credito",
                             StreamReportDocument(doc, 0, 12).ReadToEnd(),
                             systemConfig.PRINTER_NAME_CREDITO,
                             850,
                             545,
                             "courier new",
                             9,
                             true,
                             37);
            //rpt.ReportDefinition.Sections[4].ReportObjects["PáginaNdeM1"].ObjectFormat.EnableSuppress = true;
            // RawPrinterHelper.SendStringToPrinter(systemConfig.PRINTER_NAME_CREDITO, StreamReportDocument(rpt, 37, 12).ReadToEnd());
            //PrintToFile("d:\\value.txt", StreamReportDocument(rpt, 20, 12).ReadToEnd());
        }

        public void PrintNotaCredito(decimal id, bool documentoOriginal)
        {
            ReportDocument doc = GetNotaCredito(id, documentoOriginal);
            doc.ReportDefinition.Sections[4].SectionFormat.EnableSuppress = true;
            new printHelper("Nota Credito",
                             StreamReportDocument(doc, 0, 12).ReadToEnd(),
                             systemConfig.PRINTER_NAME_CREDITO,
                             850,
                             545,
                             "courier new",
                             9,
                             true,
                             37);
            //rpt.ReportDefinition.Sections[4].ReportObjects["PáginaNdeM1"].ObjectFormat.EnableSuppress = true;
            // RawPrinterHelper.SendStringToPrinter(systemConfig.PRINTER_NAME_CREDITO, StreamReportDocument(rpt, 37, 12).ReadToEnd());
            //PrintToFile("d:\\value.txt", StreamReportDocument(rpt, 20, 12).ReadToEnd());
        }
        #endregion
    }
}
